package com.yuebook.smartrpc.framework.cluster.impl;

import com.yuebook.smartrpc.framework.cluster.ClusterStrategy;
import com.yuebook.smartrpc.framework.model.ProviderService;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author honglei
 * @date 2018/11/20 上午10:28
 */
public class PollingClusterStrategyImpl implements ClusterStrategy {

    private int index = 0;
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public ProviderService select(List<ProviderService> providerServices) {
        boolean getLock = false;
        ProviderService target = null;
        try {
            getLock = lock.tryLock(10, TimeUnit.MILLISECONDS);
            if (getLock) {
                if (index >= providerServices.size()) {
                    index = 0;
                }
                target = providerServices.get(index);
                index++;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (getLock) {
                lock.unlock();
            }
        }

        return target;
    }
}
